package com.example.orderserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.orderserver.entity.Order;
import com.example.orderserver.feign.ProductApi;
import com.example.orderserver.mapper.OrderMapper;
import com.example.orderserver.service.IOrderTccService;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author whx
 * @date 2022/4/30
 */
@Slf4j
@Service
@AllArgsConstructor
public class IOrderTccServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderTccService {

    // 商品feign调用接口
    private final ProductApi productApi;

    @Override
    public void addOrder(Order order) {
        // 设置状态为未提交
        order.setStatus(0);
        // 新增订单
        this.save(order);
        // 扣减库存
        productApi.reduceInventory(order.getProduct().getId(),order.getProduct().getFrozenInventory());
    }

    @Override
    public boolean addCommit(BusinessActionContext context) {
        Order order = JSON.parseObject(context.getActionContext("order").toString(), Order.class);
        int count = this.count(Wrappers.<Order>lambdaQuery().eq(Order::getId,order.getId()));
        if(count > 0){
            order.setStatus(1);
            baseMapper.updateById(order);
        }
        log.info("事务 xid="+context.getXid()+" 提交成功");
        return true;
    }

    @Override
    public boolean addRollBack(BusinessActionContext context) {
        Order order = JSON.parseObject(context.getActionContext("order").toString(), Order.class);
        int count = this.count(Wrappers.<Order>lambdaQuery().eq(Order::getId,order.getId()));
        if(count > 0){
            // 删除数据
            this.removeById(order.getId());
        }
        log.info("事务 xid="+context.getXid()+" 回滚成功");
        return true;
    }
}
